package top.forgirl.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.servlet.HandlerInterceptor;
import top.forgirl.common.result.Result;
import top.forgirl.common.result.ResultType;
import top.forgirl.util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestToken = request.getHeader("token");
        Object sessionToken = request.getSession().getAttribute("token");
        if (JwtUtil.verifyJwt(requestToken) == null || !requestToken.equals(sessionToken)) {
            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(new Result<>(ResultType.FAILED, "please login"));
            response.getWriter().write(json);
            return false;
        }
        return true;
    }

}
